package com.uduemc.biso.node.web.service.html.impl;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.common.entities.SitePage;
import com.uduemc.biso.node.core.common.sysconfig.ArticleSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.PdtableSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.pdtablesysconfig.PdtableSysItemConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysItemConfig;
import com.uduemc.biso.node.core.entities.SArticle;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SPdtable;
import com.uduemc.biso.node.core.entities.SProduct;
import com.uduemc.biso.node.core.entities.SProductLabel;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.PdtableOne;
import com.uduemc.biso.node.core.entities.custom.PdtablePrevNext;
import com.uduemc.biso.node.core.entities.custom.Product;
import com.uduemc.biso.node.core.entities.custom.SArticlePrevNext;
import com.uduemc.biso.node.core.entities.custom.SProductPrevNext;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.html.HSystemArticleItemUdin;
import com.uduemc.biso.node.web.component.html.HSystemPdtableItemUdin;
import com.uduemc.biso.node.web.component.html.HSystemProductItemUdin;
import com.uduemc.biso.node.web.entities.AccessPage;
import com.uduemc.biso.node.web.exception.NotFound404Exception;
import com.uduemc.biso.node.web.service.ContentService;
import com.uduemc.biso.node.web.service.SRHeadService;
import com.uduemc.biso.node.web.service.byfeign.ArticleService;
import com.uduemc.biso.node.web.service.byfeign.PdtableService;
import com.uduemc.biso.node.web.service.byfeign.ProductService;
import com.uduemc.biso.node.web.service.html.HPCCompService;
import com.uduemc.biso.node.web.service.html.HSystemItemService;
import com.uduemc.biso.node.web.utils.AssetsResponseUtil;

@Service
public class HSystemItemServiceImpl implements HSystemItemService {

	private static final Logger logger = LoggerFactory.getLogger(HSystemItemServiceImpl.class);

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private ArticleService articleServiceImpl;

	@Autowired
	private ProductService productServiceImpl;

	@Autowired
	private PdtableService pdtableServiceImpl;

	@Autowired
	private HSystemArticleItemUdin hSystemArticleItemUdin;

	@Autowired
	private HSystemProductItemUdin hSystemProductItemUdin;

	@Autowired
	private HSystemPdtableItemUdin hSystemPdtableItemUdin;

	@Autowired
	private ContentService contentServiceImpl;

	@Autowired
	private SRHeadService sRHeadServiceImpl;

	@Autowired
	private HPCCompService hPCCompServiceImpl;

	@Override
	public StringBuilder html() throws NotFound404Exception, JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		String rewriteItem = requestHolder.getAccessPage().getSitePage().getRewriteItem();
		Long itemId = null;
		try {
			itemId = Long.valueOf(rewriteItem);
		} catch (NumberFormatException e) {
		}

		if (itemId == null) {
			throw new NotFound404Exception("未能通过 rewriteItem 转化成 long 数字");
		}

		String templateName = requestHolder.getAccessPage().getSitePage().getTemplateName();
		if (templateName.equals("article")) {
			return articleHtml(itemId);
		} else if (templateName.equals("product")) {
			return productHtml(itemId);
		} else if (templateName.equals("pdtableitem")) {
			return pdtableitemHtml(itemId);
		} else {
			logger.error("未能通过 templateName 找到对应的 item 详情页面 html 渲染内容! templateName: " + templateName);
		}

		return new StringBuilder("<!-- 未能通过 templateName 找到对应的 item 详情页面 html 渲染内容! templateName: " + templateName + " -->");
	}

	@Override
	public StringBuilder articleHtml(long itemId) throws NotFound404Exception, JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		SSystem system = requestHolder.getAccessPage().getSystem();

		// 获取配置
		ArticleSysConfig articleSysConfig = SystemConfigUtil.articleSysConfig(system);
		Article article = articleServiceImpl.getArticleInfo(system.getHostId(), system.getSiteId(), itemId);

		if (article != null) {
			// 回写修改 SRHead 中的 title 以及 meta 部分的内容
			sRHeadServiceImpl.remakeHRHeadTitleMate(system.getHostId(), system.getSiteId(), system.getId(), article.getSArticle().getId());
			// 浏览量 +1
			articleServiceImpl.incrementViewAuto(article.getSArticle().getHostId(), article.getSArticle().getSiteId(), article.getSArticle().getId());
		}

		// 过滤富文本部分
		if (article != null && article.getSArticle() != null) {
			String content = article.getSArticle().getContent();
			if (StringUtils.hasText(content)) {
				String filterUEditorContentWithSite = contentServiceImpl.filterUEditorContentWithSite(content);
				article.getSArticle().setContent(filterUEditorContentWithSite);
			}
		}

		// 上一个，下一个文章
		SArticlePrevNext sArticlePrevNext = null;
		if (article != null && article.getSArticle() != null && articleSysConfig.getItem().getShowPrevNext() == 1) {
			SArticle sArticle = article.getSArticle();
			Long hostId = sArticle.getHostId();
			Long siteId = sArticle.getSiteId();
			Long articleId = sArticle.getId();
			sArticlePrevNext = articleServiceImpl.prevAndNext(hostId, siteId, articleId, -1L);
		}

		AccessPage accessPage = requestHolder.getAccessPage();
		SPage sPage = accessPage.getSitePage().getSPage();

		return AssetsResponseUtil.htmlCompress(hSystemArticleItemUdin.html(sPage, articleSysConfig, article, sArticlePrevNext));
	}

	@Override
	public StringBuilder productHtml(long itemId) throws JsonParseException, JsonMappingException, IOException, NotFound404Exception {
		SSystem system = requestHolder.getAccessPage().getSystem();
		SitePage sitePage = requestHolder.getAccessPage().getSitePage();
		// 获取配置
		ProductSysConfig productSysConfig = SystemConfigUtil.productSysConfig(system);

		Product product = productServiceImpl.getInfoByHostSiteProductId(system.getHostId(), system.getSiteId(), itemId);

		if (product != null) {
			// 回写修改 SRHead 中的 title 以及 meta 部分的内容
			sRHeadServiceImpl.remakeHRHeadTitleMate(system.getHostId(), system.getSiteId(), system.getId(), product.getSProduct().getId());
		} else {
			throw new NotFound404Exception("未能找到productId对应的页面！");
		}

		// ContentServiceImpl
		// 过滤富文本部分
		List<SProductLabel> listLabelContent = product.getListLabelContent();
		if (!CollectionUtils.isEmpty(listLabelContent)) {
			for (SProductLabel sProductLabel : listLabelContent) {
				String content = sProductLabel.getContent();
				sProductLabel.setContent(contentServiceImpl.filterUEditorContentWithSite(content));
			}
		}

		// 上一个，下一个产品
		SProductPrevNext sProductPrevNext = null;
		if (product != null && product.getSProduct() != null && productSysConfig.getItem().getShowPrevNext() == 1) {
			SProduct sProduct = product.getSProduct();
			Long hostId = sProduct.getHostId();
			Long siteId = sProduct.getSiteId();
			Long articleId = sProduct.getId();
			sProductPrevNext = productServiceImpl.prevAndNext(hostId, siteId, articleId, -1L);
		}

		Integer languageId = requestHolder.getSite().getLanguageId();

		StringBuilder productDetail = AssetsResponseUtil
				.htmlCompress(hSystemProductItemUdin.html(sitePage, productSysConfig, product, languageId, sProductPrevNext));

		ProductSysItemConfig item = productSysConfig.getItem();
		int showCategory = item.getShowCategory();

		StringBuilder html = new StringBuilder();
		if (showCategory == 0) {
			html.append("<div class=\"wrap-content-in w-system w-productcom\">");
			html.append("<div class=\"w-system-in\">");
			html.append(productDetail);
			html.append("</div>");
			html.append("</div>");
			return html;
		} else {
			// 沿用列表页的分类结构设置
			showCategory = productSysConfig.getList().getStructure();
			String className = showCategory == 2 ? "side_left" : "";
			AccessPage accessPage = requestHolder.getAccessPage();
			// 当前分类数据
			SCategories category = accessPage.getSitePage().getSCategories();
			StringBuilder catehtml = hPCCompServiceImpl.catehtml(accessPage.getSitePage().getSPage(), system, category);

			html.append("<div class=\"wrap-content-in w-system w-productcom\">");
			html.append("<div class=\"w-system-in\">");
			html.append(catehtml);
			html.append("<div class=\"" + className + "\">" + productDetail + "</div>");
			html.append("</div>");
			html.append("</div>");
			return html;
		}

	}

	@Override
	public StringBuilder pdtableitemHtml(long itemId) throws JsonParseException, JsonMappingException, IOException, NotFound404Exception {
		SSystem system = requestHolder.getAccessPage().getSystem();
		SitePage sitePage = requestHolder.getAccessPage().getSitePage();
		SPage sPage = sitePage.getSPage();
		SCategories sCategories = sitePage.getSCategories();
		// 获取配置
		PdtableSysConfig pdtableSysConfig = SystemConfigUtil.pdtableSysConfig(system);
		int itemshow = pdtableSysConfig.getItem().getItemshow();
		if (itemshow != 1) {
			throw new NotFound404Exception("产品表格系统配置详情内容页不展示！");
		}

		Long hostId = system.getHostId();
		Long siteId = system.getSiteId();
		Long systemId = system.getId();

		PdtableOne pdtableOne = pdtableServiceImpl.findOkPdtableItemByHostSiteSystemIdAndId(itemId, hostId, siteId, systemId);
		if (pdtableOne == null || pdtableOne.getOne() == null && pdtableOne.getOne().getData() == null) {
			throw new NotFound404Exception("未能找到itemId对应的页面！");
		}
		// 回写修改 SRHead 中的 title 以及 meta 部分的内容
		sRHeadServiceImpl.remakeHRHeadTitleMate(system.getHostId(), system.getSiteId(), system.getId(), pdtableOne.getOne().getData().getId());

		// 过滤富文本部分
		if (pdtableOne != null && pdtableOne.getOne() != null && pdtableOne.getOne().getData() != null) {
			SPdtable data = pdtableOne.getOne().getData();
			String content = data.getContent();
			if (StringUtils.hasText(content)) {
				String filterUEditorContentWithSite = contentServiceImpl.filterUEditorContentWithSite(content);
				data.setContent(filterUEditorContentWithSite);
			}
		}

		// 上一个，下一个文章
		PdtablePrevNext pdtablePrevNext = null;
		int showprevnext = pdtableSysConfig.getItem().getShowprevnext();
		if (showprevnext == 1) {
			pdtablePrevNext = pdtableServiceImpl.findPrevNext(pdtableOne.getOne().getData(), system, -1L);
		}

		Integer languageId = requestHolder.getSite().getLanguageId();

		StringBuilder pdtableDetail = AssetsResponseUtil
				.htmlCompress(hSystemPdtableItemUdin.html(sPage, system, sCategories, pdtableOne, pdtablePrevNext, languageId));

		PdtableSysItemConfig item = pdtableSysConfig.getItem();
		int showcategory = item.getShowcategory();

		StringBuilder html = new StringBuilder();
		if (showcategory == 0) {
			html.append("<div class=\"wrap-content-in w-system w-productcom\">");
			html.append("<div class=\"w-system-in\">");
			html.append(pdtableDetail);
			html.append("</div>");
			html.append("</div>");
			return html;
		} else {
			// 沿用列表页的分类结构设置
			showcategory = pdtableSysConfig.getList().getStructure();
			String className = showcategory == 2 ? "side_left" : "";
			AccessPage accessPage = requestHolder.getAccessPage();
			// 当前分类数据
			SCategories category = accessPage.getSitePage().getSCategories();
			StringBuilder catehtml = hPCCompServiceImpl.pdtablelisthtml(accessPage.getSitePage().getSPage(), system, category);

			html.append("<div class=\"wrap-content-in w-system w-productcom\">");
			html.append("<div class=\"w-system-in\">");
			html.append(catehtml);
			html.append("<div class=\"" + className + "\">" + pdtableDetail + "</div>");
			html.append("</div>");
			html.append("</div>");
			return html;
		}
	}

}
